package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 自定义任务处理类
 */
@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;
    /**
     * 超时订单处理
     */
    @Scheduled(cron = "0 15 * * * ? ")
    public void OutOfTimeOrder(){
        log.info("定时处理超时订单,{}", LocalDateTime.now());
        //获取15分钟前的时间
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);
        //查询有无超时订单
        List<Orders>ordersList= orderMapper.selectOrderStatus(Orders.PENDING_PAYMENT,time);

        if (ordersList!=null && ordersList.size()>0){

            for (Orders orders:ordersList){
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("超时未支付,已取消");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            }
        }

    }

    /**
     * 定时处理已派送订单
     */
    @Scheduled(cron = "0 0 1 * * ? ")
    public void CompleteOrder(){
        log.info("定时处理超时订单,{}", LocalDateTime.now());
        //获取前一天的24点
        LocalDateTime time = LocalDateTime.now().minusMinutes(60);
        //查询24点前已派送订单
        List<Orders>ordersList= orderMapper.selectOrderStatus(Orders.DELIVERY_IN_PROGRESS,time);

        if (ordersList!=null && ordersList.size()>0){
            for (Orders orders:ordersList){
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }
    }
}
